package com.project.frba.bi.descriptor;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.project.frba.bi.BiUtil;
import com.project.frba.bi.exceptions.NoSuchDirectoryException;

public class DescriptorsLoader {

	static private Map<String, Descriptor> descriptors;
	
	public static synchronized void loadDescriptors(){
		File directory = new File(BiUtil.getDescriptorsDirectory());
		
		if(!directory.isDirectory()){
			throw new NoSuchDirectoryException();
		}
		
		File[] fileDescriptors = directory.listFiles(new FilenameFilter(){
			public boolean accept(File dir, String name) {
				if(name.endsWith("_descriptor.xml")){
					return true;
				}
				return false;
			}
		});
		
		descriptors = new HashMap<String, Descriptor>();
		
		for(int i=0; i < fileDescriptors.length; i++){
			Descriptor newDescriptor = new DatabaseDescriptor(fileDescriptors[i]);
			newDescriptor.load();
			descriptors.put(newDescriptor.getDescriptorName(), newDescriptor);
		}
	}

	public static Collection<Descriptor> getAllDescriptors(){
		if(descriptors == null){
			loadDescriptors();
		}
		return descriptors.values();
	}
	
	public static synchronized Descriptor getDescriptorByName(String descName){
		if(descriptors == null){
			loadDescriptors();
		}
		if(descriptors.containsKey(descName)){
			return descriptors.get(descName);
		}
		
		return null;
	}
	
	public Collection<String> getAllDescriptorsNames(){
		if(descriptors == null){
			loadDescriptors();
		}
		Collection<String> names = new ArrayList<String>();
		for(Descriptor descriptor: this.descriptors.values()){
			names.add(descriptor.getDescriptorName());
		}
		return names;
	}

	public static void reload() {
		synchronized (descriptors) {
			descriptors.clear();
			loadDescriptors();			
		}
	}	
	
}
